<?php

namespace app\controller\login;

use app\common\Message;
use app\model\iot_model\IotDevice;
use app\model\MessageModel;
use app\model\sync_model\SyncClass;
use app\model\sync_model\SyncUser;
use app\model\UserModel;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Db;
use think\response\Json;

class Login
{
    use Message;

    /**
     * 查询设备信息
     * @return bool|string|Json
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getDeviceInfo(): Json|bool|string
    {
        $data = input();
        if(!check_array_key('mac',$data)){
            return error('缺少参数mac');
        }
        $iotDeviceInfo = IotDevice::query()->where('mac',$data['mac'])->field('*')->find();
        if(empty($iotDeviceInfo)){
            return error('参数错误。暂无数据！');
        }
        return success($iotDeviceInfo,'操作成功！');
    }

    /**
     * 数据同步[报告]
     * @return bool|string|Json
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function synchronous()
    {
        $data = input();
        $key = ['device_id','data','table'];
        foreach($key as $item){
            if(!check_array_key($item,$data)){
                return error('缺少参数'.$item);
            }
        }
        Db::startTrans();
        try {
            //同步数据
//            switch ($data['table']){
//                case 'operlog':
//                    $table = SyncOperlog::query();
//                    break;
//                default:
//                    $table = SyncReport::query();
//                    break;
//            }
//            $info = $table->insertAll(json_decode($data['data'],true));
            $info = Db::name($data['table'])->insertAll(json_decode($data['data'],true));
            //如果是第一次同步。更新首次同步时间
            $first_time = IotDevice::query()->where('id',$data['device_id'])->value('first_synchronous_time');
            if($first_time == 0){
                $update['first_synchronous_time'] = time();
            }
            $update['end_synchronous_time'] = time();
            IotDevice::query()->where('id',$data['device_id'])->update($update);
            /* 提交事务 */
            Db::commit();
        }catch (\Exception $e) {
            /*回滚事务*/
            Db::rollback();
            $this->message = $e->getMessage();
            return error('同步失败:'.$this->message);
        }
        return success($info,'操作成功！');
    }

    /**
     * 数据同步[部门，用户]
     * @return bool|string|Json
     */
    public function synchronousUser(): Json|bool|string
    {
        $data = input();
        $key = ['device_id','class','user'];
        foreach($key as $item){
            if(!check_array_key($item,$data)){
                return error('缺少参数'.$item);
            }
        }
        Db::startTrans();
        try {
            //先删除部门
            $syncClass = new SyncClass();
            $syncClass->where('device_id',$data['device_id'])->delete();
            $syncClass->saveAll(json_decode($data['class'],true));
            //先删除用户
            $user = new SyncUser();
            $user->where('device_id',$data['device_id'])->delete();
            $info = $user->saveAll(json_decode($data['user'],true));
            //如果是第一次同步。更新首次同步时间
            $first_time = IotDevice::query()->where('id',$data['device_id'])->value('first_synchronous_time');
            if($first_time == 0){
                $update['first_synchronous_time'] = time();
            }
            $update['end_synchronous_time'] = time();
            IotDevice::query()->where('id',$data['device_id'])->update($update);
            /* 提交事务 */
            Db::commit();
        }catch (\Exception $e) {
            /*回滚事务*/
            Db::rollback();
            $this->message = $e->getMessage();
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
        return success($info,'操作成功！');
    }

    /**
     * 验证同步数据是否已经完成，在平台这边发一条消息给默认的超管
     * @return bool|string
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function syncSuccess(): bool|string
    {
        $data = input();
        if(!check_array_key('mac',$data)){
            return error('缺少参数mac');
        }
        if(!check_array_key('status',$data)){
            return error('缺少参数status');
        }
        $iotDevice = new IotDevice();
        $unitInfo = $iotDevice->where('mac',$data['mac'])->with(['unitName','deviceForName'])->field('company_id,name')->find();
        $message = new MessageModel();
        $messageAll = [];
        $tempWhere = [
            ['unit_id', '=', $unitInfo['company_id']],
            ['not_del', '=', 1]
        ];
        $admin = UserModel::query()->where($tempWhere)->field('id,name,role_mode')->select();
        foreach($admin as $item){
            $messageInfo['title'] = '同步成功';
            $messageInfo['time'] = time();
            $messageInfo['content'] = '物联网下的'.$unitInfo['unit_name'].$unitInfo['dev_name'].'设备资料，已完成同步！';
            $messageInfo['uid'] = $item['id'];
            $messageAll[] = $messageInfo;
        }
        $message->insertAll($messageAll);
        return success('','操作成功！');
    }
}